<?php

require_once "ZendX/JQuery/View/Helper/UiWidget.php";

class Zen_View_Helper_Elfinder_Widget extends ZendX_JQuery_View_Helper_UiWidget
{

    public function elfinder_Widget($id, $value = null, array $params = array(), array $attribs = array())
    {
        $attribs = $this->_prepareAttributes($id, $value, $attribs);
        $jquery = $this->view->jQuery();
        $jquery->enable(); 
        
        $jquery->addJavascriptFile('/cms/library/Zen/View/Helper/Elfinder/js/elfinder.min.js');
        $jquery->addJavascriptFile('/cms/library/Zen/View/Helper/Elfinder/js/i18n/elfinder.ru.js');
		$jquery->addStylesheet('/cms/library/Zen/View/Helper/Elfinder/css/elfinder.css');
        
		$js = "
			var elfinderTrigger = false;
			function load_elfinder() {
				if ( !elfinderTrigger ) {
					elfinder = true;
				    $('<div />').elfinder({
				   		url : '/elfinder/admin/connector/',
				    	lang : 'ru',
				    	places:'',
				    	dialog : { width : 800, modal : true },
				    	editorCallback : function(url) {
					    	var val=document.getElementById('$id').value;
				        	document.getElementById('$id').value = url;
					        $('#$id').trigger('change');            
				        }
				    });
				}
			}
			var el='<div id=\"{$id}newfilecont\" style=\"height:30px;margin-top:10px;padding:10px 0px 5px 10px;\">Добавить файл <a class=\"ui-state-default ui-corner-all button\" href=\"#\" id=\"elfinder_start\" style=\"padding:5px;\"><img src=\"/cms/res/icons/folder_add.png\"/></a></div>';
			$('#$id').after(el);
			$('#elfinder_start').click(function(){load_elfinder(); return false;});
			$('#$id').hide();
			$('#$id').change(function(){
				$('.$id').remove();
				var value=$(this).val();
				if(value!=''){
						var close='<div class=\"$id ui-state-default ui-corner-all\" style=\"margin-bottom:10px;padding:5px;\"><span class=\"{$id}_item\" style=\"display:inline;\">'+value+'</span><a title=\"Удалить файл\" style=\"float:left;padding:5px;\" class=\"ui-state-default ui-corner-all button {$id}_remove\" href=\"#\"><img src=\"/cms/res/icons/cancel.png\"/></a><br class=\"clear\"/></div>';
						$('#{$id}newfilecont').before(close);				
				}
				
			});
			$('.{$id}_remove').live('click',function(){
				$(this).closest('div.$id').remove();
				var value='';
				$('.{$id}_item').each(function(){
					value+=','+$(this).text();
				});
				value=value.replace(/^\,/i,'');
				$('#ri_{$id}').val(value);
				return false;
			});
			$('#$id').trigger('change');
		";
		
        
        $this->jquery->addOnLoad($js);

        return $this->view->formText($id, $value, $attribs);
    }

   
}